<!-- canvas 画笔 -->

<!-- <script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
  name: 'CanvasDemo',
})
</script> -->

<script lang="ts" setup>
import type { Canvas, CanvasContext } from '@tarojs/taro'
import { nextTick, useReady } from '@tarojs/taro'

let startX = 0
let startY = 0
let currentX = 0
let currentY = 0

let ctx: CanvasContext
let dpr: number

useReady(() => {
  nextTick(() => {
    wx.createSelectorQuery()
      .select('#canvas')
      .fields(
        {
          node: true,
          size: true,
        },
        function (res) {
          const width = res.width
          const height = res.height
          dpr = wx.getSystemInfoSync().pixelRatio
          const canvas = res.node as Canvas
          canvas.width = width * dpr
          canvas.height = height * dpr

          ctx = canvas.getContext('2d') as CanvasContext
          ctx.lineWidth = 1 * dpr
          ctx.strokeStyle = 'red'
        },
      )
      .exec()
  })
})

function touchstart(e) {
  let touch = e.changedTouches[0]
  startX = touch.x * dpr
  startY = touch.y * dpr
  ctx.moveTo(startX, startY)
}
function touchmove(e) {
  let touch = e.changedTouches[0]
  currentX = touch.x * dpr
  currentY = touch.y * dpr

  ctx.lineTo(currentX, currentY)

  ctx.stroke()
}
function touchend() {}
</script>

<template>
  <div class="DemoIndex">
    <canvas
      disable-scroll="false"
      type="2d"
      id="canvas"
      style="width: 300px; height: 300px"
      @touchstart="touchstart"
      @touchmove="touchmove"
      @touchend="touchend"
    ></canvas>
  </div>
</template>

<style lang="scss">
.DemoIndex {
  background-color: #ddd;
}
</style>
